<template>
  <Layout>
    <Form ref="form1" :model="form1" :label-width="120">
      <Row :gutter="16" class="query-form2" v-show="!switchFlag">
        <Col span="8">
          <FormItem label="活动：" prop="activityName">
            <Input class="query-form-el" type="text" v-model="form1.themeName"></Input>
          </FormItem>
        </Col>
        <i-col span="8">
          <FormItem label="创建时间：">
            <DatePicker v-model="se_date" type="datetimerange" style="width: 100%" format="yyyy-MM-dd"
                        placeholder="请选择创建时间（开始，结束）"></DatePicker>
          </FormItem>
        </i-col>
        <Col span="8">
          <div style="float: right;">
            <Button class="ivu-btn-query" icon="md-search" @click="query1">查询</Button>
            <Button class="ivu-btn-reset" style="margin-left: 10px" @click="cancel">重置</Button>
          </div>
        </Col>
      </Row>
      <Row class="query-form">
        <Col span="24">
          <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
        </Col>
      </Row>
    </Form>

    <Table ref='table' :height="tableHeight" :loading="loading" @on-selection-change='getSelectRows'
           border :columns="columns1" :data="dataTable">
    </Table>

    <Row style="margin-right:10px;">
      <Col span="24">
        <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize"
              @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
              show-total show-sizer show-elevator/>
      </Col>
    </Row>

    <Modal :title="title" :transfer=false v-model="model1" :width=800>
      <Row>
        <Col span="24">
          <Form ref="form1datacopy" :model="form1datacopy" :rules="ruleCustom" label-position="top">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="主题名称：" prop="themeName">
                  <Input type="text" v-model="form1datacopy.themeName"></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="填报时间范围：" prop="fillInTime">
                  <DatePicker v-model="form1datacopy.fillInTime" type="daterange"
                              style="width: 100%" format="yyyy-MM-dd"
                              placeholder="请选择填报时间（开始，结束）"></DatePicker>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="负责人：" prop="possess">
                  <Input type="text" v-model="form1datacopy.possess"></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="联系方式：" prop="phone">
                  <Input type="text" v-model="form1datacopy.phone"></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="主办单位：" prop="themeAddress">
                  <Input v-model="form1datacopy.themeAddress" type="text"/>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="编制人员：" prop="staff">
                  <Input v-model="form1datacopy.staffName" readonly type="text"/>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="描述：" prop="desc">
                  <Input v-model="form1datacopy.desc" type="textarea" :rows="2"/>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button @click="submit('form1datacopy')" class="ivu-btn-save" :loading="buttonLoading">确定</Button>
        <Button @click="handleCancel" class="ivu-btn-cancel">取消</Button>
      </div>
    </Modal>
    <Modal title="主题详情" class="modal-view-detail" :transfer=false v-model="model2" :width=800>
      <Row>
        <Col span="24">
          <Form :model="showdata" :label-width="120">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="主题名称：" prop="themeName">
                  {{ showdata.themeName }}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="编制日期：" prop="createDate">
                  {{ showdata.createDateStr }}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="填报开始日期：" prop="startDate">
                  {{ showdata.startDateStr }}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="填报结束日期：" prop="endDate">
                  {{ showdata.endDateStr }}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="负责人：" prop="possess">
                  {{ showdata.possess }}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="联系方式：" prop="phone">
                  {{ showdata.phone }}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="主办单位：" prop="themeAddress">
                  {{ showdata.themeAddress }}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="编制人员：" prop="staffName">
                  {{ showdata.staffName }}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="描述：" prop="desc">
                  {{ showdata.desc }}
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button class='ivu-btn-save' @click="model2=false">关闭</Button>
      </div>
    </Modal>
  </layout>
</template>

<script>
import cascaderDom from "../../../components/cascader-dom.vue"
import {
  sessionStorage
} from '../../../common/cacheUtils.js';
import {
  Api
} from '../../../api/index.js'

export default {
  components: {
    cascaderDom
  },
  data() {
    return {
      se_date: [],
      loading2: false,
      model3: false,
      buttonLoading: false,
      loading: false,
      title: "",
      saveMod: false,
      switchFlag: false,
      form1: {},
      setCurrentName: {},
      //分页参数
      pageSizeArray: [10, 20, 50],
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      currentUserId: sessionStorage('userId').getObject('userId').userId,
      currentUser: JSON.parse(sessionStorage('userId').get('userId')),
      columns1: [
        {
          title: "序号",
          width: 80,
          align: "center",
          fixed: 'left',
          render: (h, params) => {
            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
          }
        },
        {
          minWidth: 150,
          title: '主题名称',
          align: 'center',
          key: 'themeName',
        },
        {
          minWidth: 300,
          title: '主办单位',
          align: 'center',
          key: 'themeAddress',
        },
        {
          minWidth: 150,
          title: '负责人',
          align: 'center',
          key: 'possess',
        },
        {
          minWidth: 150,
          title: '联系方式',
          align: 'center',
          key: 'phone',
        },
        {
          minWidth: 150,
          title: '开始日期',
          align: 'center',
          key: 'startDate',
          render: (h, params) => {
            return h('div', [
              (this.formatDate(new Date(params.row.startDate), 'yyyy-MM-dd'))
            ]);
          }
        },
        {
          minWidth: 150,
          title: '结束日期',
          align: 'center',
          key: 'endDate',
          render: (h, params) => {
            return h('div', [
              (this.formatDate(new Date(params.row.endDate), 'yyyy-MM-dd'))
            ]);
          }
        },
        {
          minWidth: 150,
          title: '编制日期',
          align: 'center',
          key: 'createDate',
          render: (h, params) => {
            return h('div', [
              (this.formatDate(new Date(params.row.createDate), 'yyyy-MM-dd'))
            ]);
          }
        },
        {
          minWidth: 150,
          title: '编制人员',
          align: 'center',
          key: 'staffName',
        },
        {
          minWidth: 300,
          title: '描述',
          align: 'center',
          key: 'desc',
          ellipsis: true
        },
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          minWidth: 200,
          align: 'center',
          render: (h, params) => {
            let flag = (this.currentUser.loginId === this.Common.admin || this.currentUser.userId === params.row.createUserId
                || this.currentUser.userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined ||
                (this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined &&
                    params.row.orgCode && params.row.orgCode.indexOf(this.currentUser.companyCode) != -1))
            return h('div', [
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px'
                },
                on: {
                  style: {
                    fontSize: '14px',
                    color: flag ? '' : '#c5c8ce',
                    pointerEvents: flag ? '' : 'none'
                  },
                  click: () => {
                    this.showData(params, 1);
                  }
                }
              }, '详情'),
              h('Divider', {
                props: {
                  type: 'vertical',
                }
              }, ''),
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },

                on: {
                  click: () => {
                    this.showData(params, 2);
                  }
                }
              }, '修改'),
              h('Divider', {
                props: {
                  type: 'vertical',
                }
              }, ''),
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px',
                  color: flag ? 'red' : '#c5c8ce',
                  pointerEvents: flag ? '' : 'none'
                },
                on: {
                  click: () => {
                    this.$Modal.confirm({
                      title: '数据删除',
                      content: '<p>确定删除该条信息</p>',
                      okText: '确认',
                      onOk: () => {
                        this.deleteData(params);
                      },
                      cancelText: '取消'
                    });
                  }
                }
              }, '删除'),
            ]);
          }
        }
      ],
      ruleCustom: {
        possess: [{
          required: true,
          message: '  ',
          trigger: 'blur'
        }],
        themeName: [{
          required: true,
          message: '  ',
          trigger: 'blur'
        }],
        phone: [{
          validator: (rule, value, callback) => {
            if (!(/^1[3456789]\d{9}$/.test(value))) {
              callback(' ');
              this.$Message.error("请填写有效的的手机号")
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'blur'
        }],
        startDate: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        endDate: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        fillInTime: [{

          type: 'array',
          message: " ",
          trigger: 'blur',
          fields: {
            0: {type: "date", required: true, message: " "},
            1: {type: "date", required: true, message: " "}
          },
          required: true,

        }],
      },
      form1datacopy: {fillInTime: []},
      dataTable: [],
      showdata: {},
      model1: false,
      model2: false,
      add: false,
      tableHeight: 10,
      themeList: [],
    }
  },
  mounted: function () {
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
    this.query();
    this.selectThemeList();
  },
  methods: {
    switchQuery(flag) {
      this.switchFlag = flag;
      if (this.switchFlag) {
        this.tableHeight = this.tableHeight - 88;
      } else {
        this.tableHeight = this.tableHeight + 88;
      }
    },
    setUserName(data) {
      this.form1.userName = data;
    },
    setUserId(data) {
      this.form1.staff = data[data.length - 1];
    },
    selectThemeList() {
      let data = {
        currentPage: 1,
        size: 100
      }

      let url = Api.topicActivityList;
      this.$http.get(url, {
        params: data
      }).then((res) => {
        this.themeList = res.data.data.data;
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },

    pageChange(pageNum) {
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    pageSizeChange(pageSize) {
      this.pagedata.pageSize = pageSize;
      this.query();
    },
    cancel() {
      this.pagedata = {
        pageSize: 10,
        currentPage: 1
      }
      this.form1 = {};
      this.query1();
    },
    copyArray(arr) {
      return JSON.parse(JSON.stringify(arr));
    },
    showData(data, flag) {
      this.buttonLoading = false;
      if (flag == 1) {
        //查看页面
        this.showdata = data.row;
        if (this.showdata.createDate != null) {
          this.showdata.createDateStr = this.formatDate(new Date(this.showdata.createDate), 'yyyy-MM-dd');
        }
        if (this.showdata.startDate != null) {
          this.showdata.startDateStr = this.formatDate(new Date(this.showdata.startDate), 'yyyy-MM-dd');
        }
        if (this.showdata.endDate != null) {
          this.showdata.endDateStr = this.formatDate(new Date(this.showdata.endDate), 'yyyy-MM-dd');
        }
        this.model2 = true;

      } else {
        this.title = "主题修改";
        this.saveMod = false;
        this.add = false;
        this.form1datacopy = data.row;
        this.form1datacopy = JSON.parse(JSON.stringify(data.row));
        if (this.form1datacopy.startDate != null) {
          this.form1datacopy.fillInTime = [this.formatDate(new Date(this.form1datacopy.startDate), 'yyyy-MM-dd'),
            this.formatDate(new Date(this.form1datacopy.endDate), 'yyyy-MM-dd')];
        }
        this.model1 = true;
      }
    },
    getSelectRows(rows) {
      this.deleteRows = rows;
    },
    deleteData(params) {
      let url = Api.deleteTopicActivity;
      this.$http.delete(url + '/' + params.row.topicActivityId).then((res) => {
        this.$Message.success('成功');
        this.query()
      }).catch(e => {
        this.$Message.error('请求失败' + e);
      })
    },
    query1() {
      this.pagedata.currentPage = 1;
      this.query()
    },
    query() {
      this.loading = true;
      let orgId = sessionStorage('userId').getObject('userId').companyId
      let data = {
        startPage: this.pagedata.currentPage,
        size: this.pagedata.pageSize,
        orgId: orgId,
        activityType: this.$route.query.type
      };
      if (this.se_date.length != 0) {
        if (this.se_date[0] != '' && this.se_date[1] != '') {
          data.startDate = this.formatDate(new Date(this.se_date[0]), 'yyyy-MM-dd');
          data.endDate = this.formatDate(new Date(this.se_date[1]), 'yyyy-MM-dd');
        }
      }
      data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
      let url = Api.topicActivityList;
      this.$http.get(url, {
        params: data
      }).then((res) => {
        this.loading = false;
        this.dataTable = res.data.data.data;
        this.pagedata.total = res.data.data.totalSize;
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },

    reset() {
      this.se_date = ['', ''];
      this.form1 = {}
      setTimeout(() => {
        this.$refs.childUser.setCurrentUser();
      }, 50)
    },
    handleCancel() {
      this.form1datacopy = {};
      this.model1 = false;
    },
    submit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.saveMod = true;
          this.buttonLoading = true;
          if (this.form1datacopy.fillInTime.length != 0) {
            if (this.form1datacopy.fillInTime[0] != '' && this.form1datacopy.fillInTime[1] != '') {
              this.form1datacopy.startDate = this.formatDate(new Date(this.form1datacopy.fillInTime[0]), 'yyyy-MM-dd');
              this.form1datacopy.endDate = this.formatDate(new Date(this.form1datacopy.fillInTime[1]), 'yyyy-MM-dd');
              console.log(this.form1datacopy.startDate)
            }
          }
          let userId = sessionStorage('userId').getObject('userId').userId;
          let orgId = sessionStorage('userId').getObject('userId').companyId;
          this.form1datacopy.activityType = this.$route.query.type;
          if (this.add) {
            this.form1datacopy.staff = userId;
            this.form1datacopy.createUserId = userId;
            this.form1datacopy.createOrgId = orgId;
            this.$http.post(Api.saveTopicActivity, this.form1datacopy).then((res) => {
              this.$Message.success("保存成功")
              this.model1 = false;
              this.saveMod = false;
              this.query();
              this.buttonLoading = false;
            }).catch(e => {
              this.model1 = false;
              this.query();
              this.$Message.error("数据获取失败")
            })
          } else {
            this.form1datacopy.updateUserId = userId;
            this.form1datacopy.updateOrgId = orgId;
            this.$http.post(Api.updateTopicActivity, this.form1datacopy).then((res) => {
              this.$Message.success("保存成功")
              this.saveMod = false;
              this.model1 = false;
              this.query();
              this.buttonLoading = false;
            }).catch(e => {
              this.model1 = false;
              this.query();
              this.$Message.error("数据获取失败")
            })
          }
        } else {
          this.$Message.error('请填报完整!');
        }
      })
    },
    addInfo() {
      this.title = "主题新增";
      this.saveMod = false;
      let orgName = sessionStorage('userId').getObject('userId').companyName;
      let userId = sessionStorage('userId').getObject('userId').userId;
      let userName = sessionStorage('userId').getObject('userId').userName;
      this.form1datacopy = {
        fillInTime: [],
        themeAddress: orgName,
        staff: userId,
        staffName: userName
      };
      this.add = true;
      this.model1 = true;
    },
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
        }
      }
      return fmt;
    },
    padLeftZero(str) {
      return ('00' + str).substr(str.length);
    },
  }
}
</script>
<style lang='css' scoped>
@import '../../../index.css';
</style>
